package com.dollarxy.common.utils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import java.io.IOException;
import java.util.Map;

/**
 * @description: 网络请求
 * @author: wei-xhh
 * @create: 2022-07-21
 */
@Slf4j
public class OkHttpUtils {
    private static OkHttpClient client = new OkHttpClient();

    /**
     * 短信验证码
     * @param host
     * @param path
     * @param appcode
     * @param querys
     * @return
     * @throws IOException
     */
    public static String doGet(String host, String path, String appcode, Map<String,String> querys) throws IOException {
        String urlSend = host + path + "?code=" + querys.get("code") +"&phone="+ querys.get("phone") +"&sign="+ querys.get("skin") +"&skin="+ querys.get("sign");   // 【5】拼接请求链接
        // 创建一个请求 Builder,创建请求头
        Request.Builder builder = new Request.Builder();
        Request request = builder.get()
                .addHeader("Authorization","APPCODE " + appcode)
                .url(urlSend)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 社交登录
     * @param host
     * @param path
     * @param requestBodyMap
     * @return
     * @throws IOException
     */
    public static Response doPost(String host, String path, Map<String,String> requestBodyMap) throws IOException {
        String urlSend = "https://" + host + path + "";
        //创建Builder
        Request.Builder builder = new Request.Builder();
        FormBody.Builder formBuilder = new FormBody.Builder();

        //提交参数
        for ( Map.Entry<String, String> entry : requestBodyMap.entrySet() ) {
            formBuilder.add(entry.getKey(),entry.getValue());
        }

        //执行请求
        Request request = builder.post(formBuilder.build()).url(urlSend).build();
        return client.newCall(request).execute();
    }

    public static Response doGet(String host, String path,Map<String,String> querys) throws IOException{
        String urlSend = "https://" + host + path + "?access_token=" + querys.get("access_token") + "&uid=" + querys.get("uid");

        //创建Builder
        Request.Builder builder = new Request.Builder();

        //执行请求
        Request request = builder.get().url(urlSend).build();

        return client.newCall(request).execute();
    }
}
